﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Reflection;

namespace JinianNet.Reflection
{
    public class XmlHelper
    {

        public T ReadXml<T>(string root,string path) where T : new()
        {
            XmlDocument xd = new XmlDocument();
            xd.Load(path);
            T entity = new T();
            return ReadXml<T>(xd, root);
        }
        public T ReadXml<T>(XmlDocument xml, string root) where T : new()
        {
            return ReadXml<T>(xml.SelectSingleNode(root));
        }

        public T ReadXml<T>(XmlNode xml) where T : new()
        {
            T entity = new T();
            Type type = typeof(T);
            PropertyInfo[] propertys = type.GetProperties();
            foreach (PropertyInfo item in propertys)
            {
                XmlNode node = xml.SelectSingleNode(string.Concat(item.Name, "/text()"));
                if (node != null && !string.IsNullOrEmpty(node.Value))
                {
                    item.SetValue(entity, Convert.ChangeType(node.Value, item.PropertyType), null);
                }
            }
            return entity;
        }

        public void WriteXml(object entity, string root,string path)
        {
            XmlDocument xd = new XmlDocument();
            XmlElement xe = xd.CreateElement(root);
            WriteXml(entity, xe);
            xd.AppendChild(xe);
            xd.Save(path);
        }

        public void WriteXml(object entity,XmlElement element)
        {
            Type type = entity.GetType();
            PropertyInfo[] propertys = type.GetProperties();
            foreach (PropertyInfo item in propertys)
            {
                XmlElement xe =element.OwnerDocument.CreateElement(item.Name);
                object value = item.GetValue(entity, null).ToString();
                if (item.PropertyType.IsClass)
                {
                    WriteXml(item.GetValue(entity, null), xe);
                }
                else
                {
                    xe.Value = item.GetValue(entity, null).ToString();
                }
                element.AppendChild(xe);
            }
        }

    }
}
